<?php
/**
 * Created by PhpStorm.
 * User: 李一瑶
 * Date: 2018/6/28
 * Time: 16:08
 */
namespace App\Http\Repository;

use App\Http\Code;
use App\Http\Message;
use App\Http\Model\User;
use App\Http\Service\UserInterface;
use Mews\Captcha\Facades\Captcha;
use Illuminate\Support\Facades\Cache;
class UserRepository implements UserInterface
{
    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function login(array $data)
    {
        if(Captcha::check($data['captcha'])){
            unset($data['captcha']);
            $openID = session('wechat.oauth_user.default');
            $openID = $openID->getId();
            if(!$openID){
                return renderJson(\Message::WECHAT_USER_OPENID_LOSS,null,\Code::WECHAT_USER_OPENID_LOSS);
            }
            if($token = auth()->guard('api')->attempt($data)){
                $this->user->where('name','=',$data['name'])->update(['Openid'=>$openID]);
                Cache::put(md5($token),Auth::user(),60*24);
                return renderJson(Message::LOGIN_SUCCESS,'Bearer '.$token,Code::LOGIN_SUCCESS);
            }
        }else{
            return renderJson(Message::CODE_ERROR,null,Code::CODE_ERROR);
        }
    }
}